﻿using Bridge.System.Domain;
using Bridge.Shared.Models;
using Mapster;
using Mapster.Utils;
using Menus;
using Menus.Input;
using Menus.Output;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using NPOI.POIFS.Properties;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Users;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Identity;

namespace Bridge.System.Application
{
    public class MenuService : ApplicationService, IMenuService
    {
        private IRepository<Menu, Guid> _menuRepository;
        protected IdentityUserManager _userManager { get; }
        private readonly IRepository<IdentityRole> _roleRepository;
        private readonly IRepository<RoleMenu> _roleMenuRepository;
        public MenuService(IRepository<Menu, Guid> menuRepository, IdentityUserManager userManager, IRepository<IdentityRole> roleRepository, IRepository<RoleMenu> roleMenuRepository)
        {
            _menuRepository = menuRepository;
            _userManager = userManager;
            _roleRepository = roleRepository;
            _roleMenuRepository = roleMenuRepository;   
        }
        public async Task<ResponseResult<MenuOutput>> CreateAsync(CreateMenuInput input)
        {


            var oldmenu = await (await _menuRepository.GetQueryableAsync()).FirstOrDefaultAsync(a => a.Name == input.Name);
            if (oldmenu != null) {
                return ResponseResult<MenuOutput>.Fail($"菜单名为【{input.Name}】已存在！");
            }
            if(input.MenuType != "M")
            {
                var menuByPerms = await (await _menuRepository.GetQueryableAsync()).FirstOrDefaultAsync(a => a.Perms == input.Perms);
                if (menuByPerms != null)
                {
                    return ResponseResult<MenuOutput>.Fail($"权限名为【{input.Perms}】已存在！");
                }
            }
           

            Menu menu = new Menu(GuidGenerator.Create())
            {
               Name = input.Name,
            Perms = input.Perms,
            ParentId = input.ParentId.HasValue?input.ParentId.Value:Guid.Empty,
            Icon = input.Icon,
            Path = input.Path,
            ClientType = input.ClientType,
            MenuType = input.MenuType, 
            IsFrame = input.IsFrame,
            Component =string.IsNullOrEmpty(input.Component)? "Layout" : input.Component ,
            Sort = input.Sort

        };
            

           await  _menuRepository.InsertAsync(menu);
            var dto = menu.Adapt<MenuOutput>();
            return ResponseResult<MenuOutput>.Success("ok",dto);
            
        }

        public async Task<ResponseResult> DeleteAsync(IdsInput<Guid> input)
        {
            var menuList = (await _menuRepository.GetQueryableAsync()).Where(a => input.Ids.Contains(a.Id)).ToList();
            if (!menuList.Any())
            {
                return ResponseResult.Fail("记录不存在！");
            }
            await _menuRepository.HardDeleteAsync(menuList);
            return ResponseResult<MenuOutput>.Success("ok");
        }



        public async Task<ResponseResult<MenuOutput>> GetAsync(Guid id)
        {
            var menu = await _menuRepository.FirstOrDefaultAsync(a => a.Id == id);
            if(menu == null)
            {
                return ResponseResult<MenuOutput>.Fail("记录不存在！");
            }
            var dto = menu.Adapt<MenuOutput>();
            return ResponseResult<MenuOutput>.Success("ok", dto);
        }

        public async Task<PageResponseResult<MenuTreeOutput>> GetPageListAsync(GetMenuPageListInput input)
        {
            var query = (await _menuRepository.GetQueryableAsync()).WhereIf(!string.IsNullOrEmpty(input.MenuName), a => a.Name.Contains(input.MenuName));

            var totalCount = query.Count();

           if(totalCount == 0)
            {
                return PageResponseResult<MenuTreeOutput>.Fail("暂无记录");
            }
            //var list = await query.Skip(input.PageIndex * input.PageSize).Take(input.PageSize).ToListAsync();
            var list = query.ToList();
            var treeList = await BuildMenuTree(list, list[0].ParentId);
            //var dto = list.Adapt<List<MenuOutput>>();

            return PageResponseResult<MenuTreeOutput>.Success("ok", treeList, input.PageSize,input.PageIndex,totalCount); 
        }
        private async Task<List<MenuTreeOutput>> BuildMenuTree(List<Menu> menus,Guid parentId)
        {
            List<MenuTreeOutput> menuOutputs = new List<MenuTreeOutput>();
            if (menus == null)
            {
                return menuOutputs;
            }
            foreach (var item in menus)
            {


                if (parentId == item.ParentId)
                {
                    var menuoutput = new MenuTreeOutput()
                    {
                        Id = item.Id,
                       Name = item.Name,
                        Component = item.Component,
                        Path = item.Path,
                        MenuType = item.MenuType,
                        Perms = item.Perms,
                        Sort = item.Sort,
                        
                        Icon = item.Icon
                    };
                    var Children = await BuildMenuTree(menus, item.Id);

                    menuoutput.Children = Children;
               

                    menuOutputs.Add(menuoutput);
                }

            }

            return menuOutputs;
        }


        public async Task<ResponseResult<List<RouteMenuOutput>>> GetRouters()
        {
            //var jsonString = $"[{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"\",\"path\":\"/\",\"redirect\":null,\"meta\":null,\"children\":[{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"dashboard\",\"path\":\"dashboard\",\"redirect\":null,\"meta\":{{\"title\":\"控制台\",\"icon\":\"dashboard\",\"noCache\":false,\"titleKey\":\"menu.dashboard\",\"link\":\"\",\"isNew\":0}},\"component\":\"index_v1\"}}],\"component\":\"Layout\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"\",\"path\":\"/\",\"redirect\":null,\"meta\":null,\"children\":[{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"banner\",\"path\":\"Banner\",\"redirect\":null,\"meta\":{{\"title\":\"广告管理\",\"icon\":\"icon1\",\"noCache\":true,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"business/Banner\"}}],\"component\":\"Layout\"}},{{\"alwaysShow\":true,\"hidden\":false,\"name\":\"system\",\"path\":\"/system\",\"redirect\":\"noRedirect\",\"meta\":{{\"title\":\"系统管理\",\"icon\":\"system\",\"noCache\":false,\"titleKey\":\"menu.system\",\"link\":\"\",\"isNew\":0}},\"children\":[{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"user\",\"path\":\"user\",\"redirect\":null,\"meta\":{{\"title\":\"用户管理\",\"icon\":\"user\",\"noCache\":false,\"titleKey\":\"menu.systemUser\",\"link\":\"\",\"isNew\":0}},\"component\":\"system/user/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"role\",\"path\":\"role\",\"redirect\":null,\"meta\":{{\"title\":\"角色管理\",\"icon\":\"peoples\",\"noCache\":false,\"titleKey\":\"menu.systemRole\",\"link\":\"\",\"isNew\":0}},\"component\":\"system/role/index\"}},{{\"alwaysShow\":false,\"hidden\":true,\"name\":\"roleusers\",\"path\":\"roleusers\",\"redirect\":null,\"meta\":{{\"title\":\"角色分配\",\"icon\":\"people\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"system/roleusers/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"menu\",\"path\":\"menu\",\"redirect\":null,\"meta\":{{\"title\":\"菜单管理\",\"icon\":\"tree-table\",\"noCache\":false,\"titleKey\":\"menu.systemMenu\",\"link\":\"\",\"isNew\":0}},\"component\":\"system/menu/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"dept\",\"path\":\"dept\",\"redirect\":null,\"meta\":{{\"title\":\"部门管理\",\"icon\":\"tree\",\"noCache\":false,\"titleKey\":\"menu.systemDept\",\"link\":\"\",\"isNew\":0}},\"component\":\"system/dept/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"post\",\"path\":\"post\",\"redirect\":null,\"meta\":{{\"title\":\"岗位管理\",\"icon\":\"post\",\"noCache\":false,\"titleKey\":\"menu.systemPost\",\"link\":\"\",\"isNew\":0}},\"component\":\"system/post/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"dict\",\"path\":\"dict\",\"redirect\":null,\"meta\":{{\"title\":\"字典管理\",\"icon\":\"dict\",\"noCache\":false,\"titleKey\":\"menu.systemDic\",\"link\":\"\",\"isNew\":0}},\"component\":\"system/dict/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"config\",\"path\":\"config\",\"redirect\":null,\"meta\":{{\"title\":\"参数设置\",\"icon\":\"edit\",\"noCache\":false,\"titleKey\":\"menu.systemParam\",\"link\":\"\",\"isNew\":0}},\"component\":\"system/config/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"notice\",\"path\":\"notice\",\"redirect\":null,\"meta\":{{\"title\":\"通知公告\",\"icon\":\"message\",\"noCache\":false,\"titleKey\":\"menu.systemNotice\",\"link\":\"\",\"isNew\":0}},\"component\":\"system/notice/index\"}},{{\"alwaysShow\":true,\"hidden\":false,\"name\":\"log\",\"path\":\"log\",\"redirect\":\"noRedirect\",\"meta\":{{\"title\":\"日志管理\",\"icon\":\"log\",\"noCache\":false,\"titleKey\":\"menu.systemLog\",\"link\":\"\",\"isNew\":0}},\"children\":[{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"smslog\",\"path\":\"smsLog\",\"redirect\":null,\"meta\":{{\"title\":\"短信记录\",\"icon\":\"validCode\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"monitor/SmsLog\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"operlog\",\"path\":\"operlog\",\"redirect\":null,\"meta\":{{\"title\":\"操作日志\",\"icon\":\"form\",\"noCache\":false,\"titleKey\":\"menu.operLog\",\"link\":\"\",\"isNew\":0}},\"component\":\"monitor/operlog/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"logininfor\",\"path\":\"logininfor\",\"redirect\":null,\"meta\":{{\"title\":\"登录日志\",\"icon\":\"logininfor\",\"noCache\":false,\"titleKey\":\"menu.loginLog\",\"link\":\"\",\"isNew\":0}},\"component\":\"monitor/logininfor/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"sqldifflog\",\"path\":\"SqlDiffLog\",\"redirect\":null,\"meta\":{{\"title\":\"数据差异日志\",\"icon\":\"log\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"monitor/SqlDiffLog\"}}],\"component\":\"ParentView\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"commonlang\",\"path\":\"CommonLang\",\"redirect\":null,\"meta\":{{\"title\":\"多语言配置\",\"icon\":\"language\",\"noCache\":false,\"titleKey\":\"menu.systemLang\",\"link\":\"\",\"isNew\":0}},\"component\":\"system/commonLang/index\"}}],\"component\":\"Layout\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"/link/datascreen\",\"path\":\"/link/dataScreen\",\"redirect\":null,\"meta\":{{\"title\":\"数据大屏\",\"icon\":\"server\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":1}},\"component\":\"dataScreen/index\"}},{{\"alwaysShow\":true,\"hidden\":false,\"name\":\"monitor\",\"path\":\"/monitor\",\"redirect\":\"noRedirect\",\"meta\":{{\"title\":\"系统监控\",\"icon\":\"monitor\",\"noCache\":false,\"titleKey\":\"menu.monitoring\",\"link\":\"\",\"isNew\":0}},\"children\":[{{\"alwaysShow\":false,\"hidden\":true,\"name\":\"job/log\",\"path\":\"job/log\",\"redirect\":null,\"meta\":{{\"title\":\"任务日志\",\"icon\":\"log\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"monitor/job/log\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"job\",\"path\":\"job\",\"redirect\":null,\"meta\":{{\"title\":\"定时任务\",\"icon\":\"job\",\"noCache\":false,\"titleKey\":\"menu.timedTask\",\"link\":\"\",\"isNew\":0}},\"component\":\"monitor/job/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"onlineusers\",\"path\":\"onlineusers\",\"redirect\":null,\"meta\":{{\"title\":\"在线用户\",\"icon\":\"online\",\"noCache\":false,\"titleKey\":\"layout.onlineUsers\",\"link\":\"\",\"isNew\":0}},\"component\":\"monitor/onlineuser/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"server\",\"path\":\"server\",\"redirect\":null,\"meta\":{{\"title\":\"服务监控\",\"icon\":\"server\",\"noCache\":false,\"titleKey\":\"menu.serviceMonitor\",\"link\":\"\",\"isNew\":0}},\"component\":\"monitor/server/index\"}}],\"component\":\"Layout\"}},{{\"alwaysShow\":true,\"hidden\":false,\"name\":\"demo\",\"path\":\"/demo\",\"redirect\":\"noRedirect\",\"meta\":{{\"title\":\"组件示例\",\"icon\":\"zujian\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"children\":[{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"customer\",\"path\":\"customer\",\"redirect\":null,\"meta\":{{\"title\":\"主子表演示\",\"icon\":\"icon1\",\"noCache\":true,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"demo/Customer\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"icon\",\"path\":\"icon\",\"redirect\":null,\"meta\":{{\"title\":\"图标icon\",\"icon\":\"icon1\",\"noCache\":false,\"titleKey\":\"menu.icon\",\"link\":\"\",\"isNew\":0}},\"component\":\"components/icons/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"codecompare\",\"path\":\"codeCompare\",\"redirect\":null,\"meta\":{{\"title\":\"代码比较\",\"icon\":\"\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"tool/codeCompare\"}}],\"component\":\"Layout\"}},{{\"alwaysShow\":true,\"hidden\":false,\"name\":\"tool\",\"path\":\"/tool\",\"redirect\":\"noRedirect\",\"meta\":{{\"title\":\"系统工具\",\"icon\":\"tool\",\"noCache\":false,\"titleKey\":\"menu.systemTools\",\"link\":\"\",\"isNew\":0}},\"children\":[{{\"alwaysShow\":false,\"hidden\":true,\"name\":\"/gen/edittable\",\"path\":\"/gen/editTable\",\"redirect\":null,\"meta\":{{\"title\":\"生成修改\",\"icon\":\"\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"tool/gen/editTable\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"build\",\"path\":\"build\",\"redirect\":null,\"meta\":{{\"title\":\"表单构建\",\"icon\":\"build\",\"noCache\":false,\"titleKey\":\"menu.formBuild\",\"link\":\"\",\"isNew\":0}},\"component\":\"tool/build/index\"}},{{\"alwaysShow\":false,\"hidden\":true,\"name\":\"/article/publish\",\"path\":\"/article/publish\",\"redirect\":null,\"meta\":{{\"title\":\"发布文章\",\"icon\":\"log\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"system/article/publish\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"gen\",\"path\":\"gen\",\"redirect\":null,\"meta\":{{\"title\":\"代码生成\",\"icon\":\"code\",\"noCache\":false,\"titleKey\":\"menu.codeGeneration\",\"link\":\"\",\"isNew\":0}},\"component\":\"tool/gen/index\"}},{{\"alwaysShow\":true,\"hidden\":false,\"name\":\"email\",\"path\":\"email\",\"redirect\":\"noRedirect\",\"meta\":{{\"title\":\"邮件管理\",\"icon\":\"email\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"children\":[{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"email\",\"path\":\"email\",\"redirect\":null,\"meta\":{{\"title\":\"邮件模板\",\"icon\":\"icon1\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"tool/email/emailTpl\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"emaillog\",\"path\":\"emailLog\",\"redirect\":null,\"meta\":{{\"title\":\"邮件记录\",\"icon\":\"emailLog\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"tool/email/emailLog\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"sendemail\",\"path\":\"sendEmail\",\"redirect\":null,\"meta\":{{\"title\":\"发送邮件\",\"icon\":\"emailSend\",\"noCache\":false,\"titleKey\":\"menu.sendEmail\",\"link\":\"\",\"isNew\":0}},\"component\":\"tool/email/sendEmail\"}}],\"component\":\"ParentView\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"swagger\",\"path\":\"swagger\",\"redirect\":null,\"meta\":{{\"title\":\"系统接口\",\"icon\":\"swagger\",\"noCache\":false,\"titleKey\":\"menu.systemInterface\",\"link\":\"\",\"isNew\":0}},\"component\":\"tool/swagger/index\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"file\",\"path\":\"file\",\"redirect\":null,\"meta\":{{\"title\":\"文件存储\",\"icon\":\"upload\",\"noCache\":false,\"titleKey\":\"menu.fileStorage\",\"link\":\"\",\"isNew\":0}},\"component\":\"tool/file/index\"}},{{\"alwaysShow\":true,\"hidden\":false,\"name\":\"article\",\"path\":\"article\",\"redirect\":\"noRedirect\",\"meta\":{{\"title\":\"文章管理\",\"icon\":\"documentation\",\"noCache\":false,\"titleKey\":\"menu.systemArticle\",\"link\":\"\",\"isNew\":0}},\"children\":[{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"index\",\"path\":\"index\",\"redirect\":null,\"meta\":{{\"title\":\"文章列表\",\"icon\":\"list\",\"noCache\":false,\"titleKey\":\"menu.articleList\",\"link\":\"\",\"isNew\":0}},\"component\":\"system/article/manager\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"articlecategory\",\"path\":\"ArticleCategory\",\"redirect\":null,\"meta\":{{\"title\":\"文章目录\",\"icon\":\"tree-table\",\"noCache\":false,\"titleKey\":null,\"link\":\"\",\"isNew\":0}},\"component\":\"system/article/articleCategory\"}}],\"component\":\"ParentView\"}}],\"component\":\"Layout\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"http://www.izhaorui.cn/doc\",\"path\":\"http://www.izhaorui.cn/doc\",\"redirect\":null,\"meta\":{{\"title\":\"官方文档\",\"icon\":\"link\",\"noCache\":false,\"titleKey\":\"\",\"link\":\"http://www.izhaorui.cn/doc\",\"isNew\":0}},\"component\":\"Layout\"}},{{\"alwaysShow\":false,\"hidden\":false,\"name\":\"https://www.izhaorui.cn/doc/quickstart.html\",\"path\":\"https://www.izhaorui.cn/doc/quickstart.html\",\"redirect\":null,\"meta\":{{\"title\":\"快速入门🚀\",\"icon\":\"\",\"noCache\":false,\"titleKey\":null,\"link\":\"https://www.izhaorui.cn/doc/quickstart.html\",\"isNew\":0}},\"component\":\"Layout\"}}]";
            //var myObject = JsonConvert.DeserializeObject<List<RouteMenuOutput>>(jsonString);
            //return ResponseResult<List<RouteMenuOutput>>.Success("ok", myObject);
            //获取当前用户信息
            var user = await _userManager.GetByIdAsync(CurrentUser.Id.Value);
            if(user == null)
            {
               return ResponseResult<List<RouteMenuOutput>>.Fail("用户不存在！");
            }
            //获取用户角色信息
            var rolseNameList =await _userManager.GetRolesAsync(user);
            if(rolseNameList == null)
            {
                return ResponseResult<List<RouteMenuOutput>>.Fail("角色信息不存在！");
            }
            var rolseIdList = (await _roleRepository.GetQueryableAsync()).Where(a=>rolseNameList.Contains(a.Name)).Select(a=>a.Id).ToList();

            //获取角色对应的所有菜单id
           var menuIds =(await _roleMenuRepository.GetQueryableAsync()).Where(a=>rolseIdList.Contains(a.RoleId)).Select(a=>a.MenuId).ToList();
            if(!menuIds.Any())
            {
                return ResponseResult<List<RouteMenuOutput>>.Fail("未获取到菜单信息！");
            }
            //获取用户所有的菜单信息
            var menus = (await _menuRepository.GetQueryableAsync()).Where(a=>menuIds.Contains(a.Id)).ToList();
            var dto = await BuildMenus(menus,Guid.Empty);

            return ResponseResult<List<RouteMenuOutput>>.Success("ok", dto);
/*
            $"[{
	"alwaysShow": false,
	"hidden": false,
	"name": "",
	"path": "/",
	"redirect": null,
	"meta": null,
	"children": [{
		"alwaysShow": false,
		"hidden": false,
		"name": "dashboard",
		"path": "dashboard",
		"redirect": null,
		"meta": {
			"title": "控制台",
			"icon": "dashboard",
			"noCache": false,
			"titleKey": "menu.dashboard",
			"link": "",
			"isNew": 0
		},
		"component": "index_v1"
	}],
	"component": "Layout"
}, {
	"alwaysShow": true,
	"hidden": false,
	"name": "demo",
	"path": "/demo",
	"redirect": "noRedirect",
	"meta": {
		"title": "组件示例",
		"icon": "zujian",
		"noCache": false,
		"titleKey": null,
		"link": "",
		"isNew": 0
	},
	"children": [{
			"alwaysShow": false,
			"hidden": false,
			"name": "icon",
			"path": "icon",
			"redirect": null,
			"meta": {
				"title": "图标icon",
				"icon": "icon1",
				"noCache": false,
				"titleKey": "menu.icon",
				"link": "",
				"isNew": 0
			},
			"component": "components/icons/index"
		},
		{
			"alwaysShow": false,
			"hidden": false,
			"name": "customer",
			"path": "customer",
			"redirect": null,
			"meta": {
				"title": "主子表演示",
				"icon": "icon1",
				"noCache": true,
				"titleKey": null,
				"link": "",
				"isNew": 0
			},
			"component": "demo/Customer"
		}
	]
}]"
*/
        }

        private async Task<List<RouteMenuOutput>> BuildMenus(List<Menu> menus, Guid parentId)
        {
            List<RouteMenuOutput> menuOutputs = new List<RouteMenuOutput>();
            if (menus == null)
            {
                if (menus == null)
                {
                    return menuOutputs;
                }
            }
            foreach (var item in menus)
            {
               
                
                if (parentId == item.ParentId)
                {
                    var menuoutput = new RouteMenuOutput()
                    {
                        Meta = new MetaOutput() { Title = item.Name, TitleKey = item.Perms, Link = "", NoCache = false, Icon = "",IsNew=0},
                        Component = item.Component,
                        Path = item.Path,

                    };
                    var Children = await BuildMenus(menus, item.Id);

                   menuoutput.Name = item.Path;
                    menuoutput.Children = Children;
                    if(menuoutput.Meta != null)
                    {
                       menuoutput.AlwaysShow = false;
                    }
                    else
                    {
                        menuoutput.AlwaysShow = true;
                    }

                    menuOutputs.Add(menuoutput);
                }
               
            }

            return menuOutputs;
        }

        public async Task<ResponseResult<MenuOutput>> UpdateAsync(UpdateMenuInput input)
        {
            var menu = await _menuRepository.FirstOrDefaultAsync(a=>a.Id == input.Id);
            if (menu == null)
            {
                return ResponseResult<MenuOutput>.Fail("记录不存在！");
            }
            menu.ClientType = input.ClientType;
            menu.MenuType = input.MenuType;
            menu.Name = input.Name;
            menu.Path = input.Path;
            menu.Sort = input.Sort;
            menu.Icon = input.Icon;
            menu.IsFrame = input.IsFrame;
            menu.LastModificationTime = DateTime.Now;
            menu.LastModifierId = CurrentUser.Id;
            menu.Component =input.Component;
            menu.Perms = input.Perms;
            await _menuRepository.UpdateAsync(menu);
            var dto = menu.Adapt<MenuOutput>();
            return ResponseResult<MenuOutput>.Success("ok",dto);
        }

        public async Task<ResponseResult<MenuTreeSelectDto>> GetMenuTreeSelect(Guid roleId)
        {
            var role =await _roleRepository.FirstOrDefaultAsync(a=>a.Id == roleId);
            if (role == null)
            {
                return ResponseResult<MenuTreeSelectDto>.Fail("不存在该记录！");
            }

            var menuIds =(await _roleMenuRepository.GetQueryableAsync()).Where(a=>a.RoleId == role.Id).Select(a=>a.MenuId).ToList();
            
            var menuList = (await _menuRepository.GetQueryableAsync()).ToList();

            var TressMenuList =   await BuildMenuTreeSelect(menuList, Guid.Empty);

            var dto = new MenuTreeSelectDto() { CheckedKeys = menuIds, Menus = TressMenuList };
            return ResponseResult<MenuTreeSelectDto>.Success("操作成功！", dto);
        }

        public async Task<List<MenuTreeSelectOutput>> BuildMenuTreeSelect(List<Menu> menus, Guid parentId)
        {
            List<MenuTreeSelectOutput> menuOutputs = new List<MenuTreeSelectOutput>();
            if (menus == null)
            {
                if (menus == null)
                {
                    return menuOutputs;
                }
            }
            foreach (var item in menus)
            {


                if (parentId == item.ParentId)
                {
                    var menuoutput = new MenuTreeSelectOutput()
                    {
                        Id = item.Id,
                        Name = item.Name

                    };
                    var Children = await BuildMenuTreeSelect(menus, item.Id);

                    menuoutput.Name = item.Name;
                    menuoutput.Children = Children;
                    

                    menuOutputs.Add(menuoutput);
                }

            }

            return menuOutputs;
        }
    }
}
